package com.lifei.service;

import com.lifei.domain.Order;
import com.lifei.domain.Product;
import com.lifei.repository.OrderRepository;
import com.lifei.repository.ProductRepository;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Optional;
import java.util.concurrent.TimeUnit;

@Component
@RocketMQMessageListener(topic = "springboot-mq",consumerGroup = "springboot-mq-consumer-1")
public class Consumer implements RocketMQListener<Order> {

    @Autowired
    private OrderRepository orderRepository;
    @Autowired
    private ProductRepository productRepository;
    @Autowired
    private StringRedisTemplate redisTemplate;


    @Override
    public void onMessage(Order order) {

        System.out.println("... 消费者处理订单消息 ...");

        order = orderRepository.save(order);
        System.out.println("... 生成订单id：" + order.getId() + " 订单入库 ...");

        Product product = productRepository.findOneById(order.getProductId());
        product.setNumber(product.getNumber() - 1);
        System.out.println("... 扣减库存 ...");
        productRepository.save(product);

        redisTemplate.opsForValue().set("order:" + order.getId(),"",15, TimeUnit.SECONDS);

    }
}
